<template>
  <div>
    <form-show :only-preview="true" :visible.sync="drawerVisible" :form-data="formData" size="100%"
               :generate-conf="generateConf"
    />
  </div>
</template>

<script>
  import {
    deepClone,
    getParams
  } from '@/utils/index'

  import {
    debounce
  } from 'throttle-debounce'

  import {
    formConf
  } from '@/components/generator/config'

  import drawingDefalut from '@/components/generator/drawingDefalut'

  import {
    getDrawingList,
    saveDrawingList,
    getIdGlobal,
    saveIdGlobal,
    getFormConf,
    saveFormConfToDB,
    cleareFormConf,
    clearDrawingList,
    getFormConfToDB,
    updateFormConfToDB,
    getFormDataToDB,
    saveFormDataToDB,
    updateFormDataToDB
  } from '@/utils/db'

  import formShow from './form-show.vue'

  const drawingListInDB = getDrawingList()
  const formConfInDB = getFormConf()
  const opParams = getParams(window.location.search)

  export default {
    components: {
      formShow
    },
    data() {
      return {
        formConf,
        // 是否展示
        drawerVisible: false,
        // 布局列表
        drawingList: null,
        // 表单数据
        formData: {},
        // 初始化数据
        data: {},
        // 弹窗配置
        generateConf: null,
        getFormConfToDBDebounce: debounce(340, getFormConfToDB),
        getFormDataToDBDebounce: debounce(340, getFormDataToDB),
        saveFormDataToDBDebounce: debounce(340, saveFormDataToDB),
        updateFormDataToDBDebounce: debounce(340, updateFormDataToDB),
        activeId: drawingDefalut[0].formId,
        activeData: drawingDefalut[0]
      }
    },
    mounted() {
      this.init()
    },
    methods: {
      init() {
        if (Array.isArray(drawingListInDB) && drawingListInDB.length > 0) {
          this.drawingList = drawingListInDB
        } else {
          this.drawingList = drawingDefalut
        }

        this.activeFormItem(this.drawingList[0])
        if (formConfInDB) {
          this.formConf = formConfInDB
        }

        if (opFormId) {
          this.getFormConfToDBDebounce(opFormId, res => {
            this.drawingList = res.fields
            for (const key in this.formConf) {
              this.formConf[key] = res[key]
            }

            this.generateConf = {
              fileName: res.formRef,
              type: res.pageType
            }

            // 该项代表修改数据
            if (opParams.dataId) {
              this.getFormDataToDBDebounce(res.formRef, opParams.dataId, res => {
                this.data = res
                this.execRun()
              }, err => {
                this.$notify({
                  title: '数据初始化失败',
                  message: err.msg,
                  type: 'fail'
                })
              })
            } else {
              this.execRun()
            }
          }, err => {
            this.$notify({
              title: '表单初始化失败',
              message: err.msg,
              type: 'fail'
            })
          })
        }

        window.addEventListener('message', this.msg)
      },

      AssembleFormData() {
        this.formData = {
          fields: deepClone(this.drawingList),
          ...this.formConf
        }

        // 赋予初值
        if (this.formData && this.formData.fields) {
          this.formData.fields.forEach(field => {
            if (this.data[field.__vModel__]) {
              field.__config__.defaultValue = this.data[field.__vModel__]
            }
          })

          this.formData.defaultData = this.data
        }
      },

      // 运行
      execRun(data) {
        this.AssembleFormData()
        this.drawerVisible = true
      },

      activeFormItem(currentItem) {
        this.activeData = currentItem
        this.activeId = currentItem.__config__.formId
      },

      // 处理消息
      msg(res) {
        if (event.data.type === 'submit') {
          const { data } = event.data

          if (this.formData.url) {
            this.$axios({
              method: this.data.id ? 'put' : 'post',
              url: this.formData.url,
              data
            }).then(res => {
              this.$notify({
                title: '保存成功',
                message: '',
                type: 'success'
              })

              closeMe()
            }).catch(err => {
              console.error(err)
              this.$notify({
                title: '保存失败',
                message: err.msg,
                type: 'fail'
              })
            })
          } else if (this.data.id) {
              this.updateFormDataToDBDebounce(this.formData.formRef, this.data.id, data,
                success => {
                  this.$notify({
                    title: '更新成功',
                    message: '',
                    type: 'success'
                  })

                  closeMe()
                },
                err => {
                  console.error(err)
                  this.$notify({
                    title: '更新失败',
                    message: err.msg,
                    type: 'fail'
                  })
                })
            } else {
              this.saveFormDataToDBDebounce(this.formData.formRef, data,
                success => {
                  this.$notify({
                    title: '保存成功',
                    message: '',
                    type: 'success'
                  })

                  closeMe()
                },
                err => {
                  console.error(err)
                  this.$notify({
                    title: '保存失败',
                    message: '',
                    type: 'fail'
                  })
                })
            }
        }
      }
    }

  }
</script>

<style>

</style>
